<template>
  <div class="orderConfirm">
    <!-- 顶部导航栏 -->
    <van-sticky :offset-top="0">
      <van-nav-bar
        title="订单确认"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
    </van-sticky>

    <!-- 提交按钮 -->
    <div class="confirm_btn" @click="confirm">确认提交</div>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from "vuex";
import { Dialog } from "vant";
export default {
  data() {
    return {
      // 选择的时间
      timeValue: new Date(),
      // 当前时间
      currentDate: new Date(),
      // 日期选择器显示控制
      show: false,
      // 被选中的地址id
      chosenAddressId: "1",
      // 面板弹出控制
      showAddress: false,
      // 姓名
      username: "",
      // 电话
      tel: "",
      // 地址
      address: "",
      // 充值框弹出
      balanceShow: false,
      // 充值金额
      balance: "",
    };
  },
  created() {
    // 获取用户信息
    this.getUserInfo();
    // 获取地址信息  并设置默认地址
    this.getAddressData().then((r) => {
      // 设置默认地址
      // 姓名
      this.username = this.addressData.list[0].username;
      // 电话
      this.tel = this.addressData.list[0].telephone;
      // 地址
      this.address =
        this.addressData.list[0].province +
        this.addressData.list[0].city +
        this.addressData.list[0].area +
        this.addressData.list[0].address;
      // 地址列表默认id
      this.chosenAddressId = this.addressData.list[0].id;
    });
  },
  computed: {
    // 获取保存的订单信息
    ...mapState("shopcart", ["orderLines"]),
    // 获取订单总价
    ...mapGetters("shopcart", ["total"]),
    // 获取地址列表
    ...mapState("address", ["addressData"]),
    // 获取用户信息
    ...mapState("user", ["userInfo"]),
    // 根据地址数据生成匹配组件的地址数据
    addressList() {
      // 筛选地址数据 生成匹配组件的数据
      let addressArr = this.addressData.list;
      let addressList = [];
      if (!addressArr) {
        return;
      }
      addressArr.forEach((item, index) => {
        let addressObj = {};
        (addressObj.id = item.id),
          (addressObj.name = item.username),
          (addressObj.tel = item.telephone),
          (addressObj.address =
            item.province + item.city + item.area + item.address),
          (addressObj.isDefault = item.isDefault);
        addressList.push(addressObj);
      });
      return addressList;
    },
  },
  methods: {
    // 获取地址数据
    ...mapActions("address", ["getAddressData"]),
    // 获取用户信息
    ...mapActions("user", ["getUserInfo"]),
    // 提交订单
    ...mapActions("order", ["SubmitOrder"]),
    // 余额充值
    ...mapActions("recharge", ["getRecharge"]),
    // 获取地址数据
    getAddressList() {
      // 打开actionSheet
      this.showAddress = true;
      // 获取地址数据
      this.getAddressData();
    },
    // 选择地址确认
    onSave() {
      // console.log(this.chosenAddressId);
      // 根据地址id筛选当前选择的地址
      let addressObj = this.addressData.list.filter((item, index) => {
        return item.id === this.chosenAddressId;
      });
      // 根据选择的地址进行地址的更新
      this.username = addressObj[0].username;
      this.tel = addressObj[0].telephone;
      this.address =
        addressObj[0].province +
        addressObj[0].city +
        addressObj[0].area +
        addressObj[0].address;
      // 隐藏地址选择面板
      this.showAddress = false;
    },
    // 时间确认
    confirmDate(value) {
      // 时间赋值
      this.timeValue = value;
      // 关闭时间选择
      this.show = false;
    },
    cancelDate() {
      this.show = false;
    },
    // 日期选择器格式
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      if (type === "hour") {
        return val + "时";
      }
      if (type === "minute") {
        return val + "分";
      }
      return val;
    },
    // 提交订单
    confirm() {
      // 保存订单信息
      // 参数
      var obj = {
        addressId: this.chosenAddressId,
        customerId: this.userInfo.id,
        serviceTime: this.timeValue.getTime(),
        orderLines: Array.from(this.orderLines.values()),
      };
      this.SubmitOrder(obj).then((response) => {
        // console.log(response);
        if (response.data.message == "余额不足!") {
          Dialog.confirm({
            confirmButtonColor: "#7879FF",
            message: "当前余额不足，是否充值？",
          })
            .then(() => {
              // on confirm
              // 弹出充值框
              this.balanceShow = true;
            })
            .catch(() => {
              // on cancel
            });
        } else if (response.data.message == "操作成功") {
          this.$notify({
            type: "success",
            message: response.data.message,
          });
          // 路由跳转至订单页面
          this.$router.push({ path: "/manager/order" }).then((res) => {
            // 获取订单数据
          });
        } else {
          this.$notify({
            type: "danger",
            message: response.data.message,
          });
        }
      });
    },
    // 充值金额校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      if (val < 0 || val > 1000) {
        return false;
      } else {
        return true;
      }
    },
    // 充值
    topUp() {
      console.log(this.balance, this.userInfo.id);
      let data = {
        customerId: this.userInfo.id,
        money: this.balance,
      };
      this.getRecharge(data).then((r) => {
        console.log(r);
        if (r.data.status == 200) {
          this.$notify({
            type: "success",
            message: r.data.message,
          });
          this.balanceShow = false;
        } else {
          this.$notify({
            type: "danger",
            message: r.data.message,
          });
        }
      });
      // 实现充值逻辑
    },
    // 取消弹框
    toClose() {
      // 余额置空
      this.balance = "";
    },
    // 返回上一级页面
    onClickLeft() {
      this.$router.go(-1);
      console.log();
      setTimeout(() => {
        this.$store.state.shopcart.orderLines.clear();
      }, 500);
    },
  },
};
</script>

<style scoped>
/* 提交按钮 */
.confirm_btn {
  width: 53%;
  height: 40px;
  background-image: linear-gradient(to right, #7579ff, #bf73ff);
  text-align: center;
  color: #fff;
  border-radius: 22px;
  line-height: 40px;
  margin: 0 auto;
  margin-top: 2em;
  cursor: pointer;
}
.van-icon-edit {
  display: none;
}
/* 充值 */
.cz {
  height: 80px;
  text-align: center;
}
</style>